import { Directive, ElementRef, EventEmitter, Input, Output, Renderer2 } from '@angular/core';
import Editor from 'wangeditor';

@Directive({
	selector: '[editor]',
})
export class WangEditorDirective {
	editor = null;

	@Input()
	set txtHtml(v) {
		if (!this.editor.isFocus) {
			this.editor.txt.html(v);
		}
	}

	@Output()
	txtHtmlChange = new EventEmitter();

	constructor(private el: ElementRef, private r2: Renderer2) {
		const parent = el.nativeElement;
		r2.setStyle(parent, 'border', '1px solid #ddd')
		r2.setStyle(parent, 'overflow', 'hidden')
		const menu = r2.createElement('div');
		r2.setStyle(menu, 'position', 'sticky')
		r2.setStyle(menu, 'top', '0')
		r2.setStyle(menu, 'z-index', '2')
		r2.setStyle(menu, 'display', 'none')
		const content = r2.createElement('div');
		r2.setStyle(content, 'height', 'calc(100% - 40px)')
		r2.addClass(content, 'tjpld-editor')
		r2.appendChild(parent, menu);
		r2.appendChild(parent, content);
		this.editor = new Editor(menu, content);
		this.editor.config.zIndex = 1;
		this.editor.config.focus = false;
		this.editor.config.onfocus = () => {
			r2.setStyle(menu, 'display', '');
		}
		this.editor.config.onblur = () => {
			r2.setStyle(menu, 'display', 'none');
		}
		this.editor.config.onchange = (html) => {
			this.txtHtmlChange.emit(html);
		};
		this.editor.create();
	}
}
